<template>
  <div class="page-prod-add-or-update">
    <!-- 步骤 -->
    <div class="post-step">
      <div
        class="step-item"
        :class="{ active: postingSteps === 1 || postingSteps === 2 }"
      >
        <!-- 01、选择商品类目 -->
        <div class="step-txt">
          01、{{ $t("product.selectProductCategory") }}
        </div>
      </div>
      <div
        class="step-item"
        :class="{ active: postingSteps === 2 }"
      >
        <!-- 02、编辑商品信息 -->
        <div class="step-txt">
          02、{{ $t("product.editProductInfo") }}
        </div>
      </div>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      label-width="110px"
      @submit.prevent
    >
      <!-- 基本信息  -->
      <div
        v-show="postingSteps === 1"
        class="tittle"
      >
        {{ $t("product.basicInformation") }}
      </div>

      <div
        v-show="postingSteps === 1"
        class="basic-info"
      >
        <!-- 选择语言 -->
        <el-form-item
          v-show="postingSteps === 1"
          :label="$t('product.selectLanguage')"
          :label-width="
            $t('language') === 'English' ? '146px' : '100px'
          "
          class="prod-name-box"
        >
          <el-select
            v-model="curLang"
            multiple
            :placeholder="$t('product.tip1')"
            @change="onSelectLang"
          >
            <el-option
              v-for="item in langOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <div
            style="color: #999"
            class="el-form-item-tips"
          >
            {{ $t("product.postProductTips2") }}
          </div>
        </el-form-item>
        <div
          v-show="postingSteps === 1"
          class="prod-name-box"
        >
          <el-form-item
            :label="$t('product.prodName')"
            prop="prodNameCn"
            class="is-required"
            :label-width="
              $t('language') === 'English' ? '146px' : '100px'
            "
          >
            <el-input
              v-model="prodNameCn"
              maxlength="60"
            />
            <div
              style="color: #999"
              class="el-form-item-tips"
            >
              商品名称建议：商品描述+属性，长度不超过60个字符
            </div>
          </el-form-item>
          <el-form-item
            v-if="curLang.includes(2)"
            label-width="0"
            prop="prodNameEn"
            class="en-margin"
          >
            <el-input
              v-model="prodNameEn"
              maxlength="60"
            />
            <div
              style="color: #999"
              class="el-form-item-tips"
            >
              The suggestion: description + attribute, length cannot exceed 60
            </div>
          </el-form-item>
        </div>
        <!-- 商品卖点 -->
        <div
          v-show="postingSteps === 1"
          class="prod-name-box"
        >
          <el-form-item
            :label="$t('product.productSellingPoints')"
            prop="briefCn"
            :label-width="
              $t('language') === 'English' ? '146px' : '100px'
            "
          >
            <el-input
              v-model="briefCn"
              maxlength="100"
            />
            <div
              style="color: #999"
              class="el-form-item-tips"
            >
              商品卖点展示在商品名称下面，长度不超过100个字符
            </div>
          </el-form-item>
          <el-form-item
            v-if="curLang.includes(2)"
            label-width="0"
            prop="briefEn"
            class="en-margin"
          >
            <el-input
              v-model="briefEn"
              maxlength="100"
            />
            <div
              style="color: #999"
              class="el-form-item-tips"
            >
              Displayed under the title, the length cannot exceed 100
            </div>
          </el-form-item>
        </div>
        <!-- 商品图片 -->
        <el-form-item
          :label="$t('temp.proImg')"
          class="labelName upload-box"
          :label-width="
            $t('language') === 'English' ? '146px' : '100px'
          "
        >
          <ImgsUpload
            v-model="dataForm.imgs"
            :limit="9"
          />
          <span style="color: #999">{{ $t("admin.recommImgSize") }} 800*800，{{
            $t("product.picUploadTips")
          }}</span>
        </el-form-item>

        <!-- 商品视频 -->
        <el-form-item
          :label="$t('product.productVideo')"
          :label-width="
            $t('language') === 'English' ? '140px' : '100px'
          "
          class="video-k upload-box"
        >
          <VideoUpload v-model="dataForm.video" />
          <div
            v-if="dataForm.video"
            class="video-del-btn default-btn"
            @click="onDeleteVideo"
          >
            删除视频
          </div>
        </el-form-item>

        <!-- 产品分类 -->
        <el-form-item
          :label="$t('product.platforation')"
          :label-width="
            $t('language') === 'English' ? '160px' : '100px'
          "
          prop="categoryId"
          :rules="[
            { required: true, message: $t('product.pleCategory') },
          ]"
          class="cascader-box"
        >
          <el-col :span="8">
            <el-cascader
              v-model="category.selected"
              :options="category.list"
              :props="category.props"
              @change="handleCategoryChange"
            />
          </el-col>
        </el-form-item>

        <!-- 产品分组 -->
        <el-form-item
          :label="$t('product.productGrouping')"
          :label-width="
            $t('language') === 'English' ? '160px' : '100px'
          "
          class="cascader-box"
        >
          <el-col :span="8">
            <el-select
              v-model="dataForm.tagList"
              multiple
              :placeholder="$t('tip.select')"
              class="select-box"
            >
              <el-option
                v-for="item in tags"
                :key="item.id"
                :label="item.title"
                :value="item.id"
                class="options"
              />
            </el-select>
          </el-col>
        </el-form-item>
      </div>
      <!-- 预售发货时间 -->
      <el-form-item
        v-show="postingSteps === 1"
        :label="$t('product.isPresell')"
        :label-width="
          $t('language') === 'English' ? '270px' : '100px'
        "
        style="padding-left: 60px"
      >
        <el-radio-group v-model="dataForm.preSellStatus">
          <el-radio :label="0">
            {{ $t("station.close") }}
          </el-radio>
          <el-radio :label="1">
            {{ $t("station.open") }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-show="postingSteps === 1"
        v-if="dataForm.preSellStatus === 1"
        :rules="[
          {
            required: true,
            message: $t('product.thePreSaleDtBeEmpty'),
          },
        ]"
        style="padding-left: 54px"
        :label="$t('product.presellTime')"
        :label-width="
          $t('language') === 'English' ? '224px' : '106px'
        "
        prop="preSellTime"
      >
        <el-date-picker
          v-model="dataForm.preSellTime"
          :placeholder="$t('product.choosePreSaleTime')"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="date"
          format="YYYY-MM-DD"
        />
      </el-form-item>

      <!-- 规格库存 -->
      <div
        v-show="postingSteps === 1"
        class="tittle"
      >
        {{ $t("product.specificationStock") }}
      </div>
      <div
        v-show="postingSteps === 1"
        class="basic-info"
      >
        <SkuTag
          ref="skuTagRef"
          :sku-list="dataForm.skuList"
          @change="skuTagChangeSkuHandler"
          @change-sku-img="changeSkuImg"
        />

        <SkuTableProd
          ref="skuTableRef"
          v-model="dataForm.skuList"
          v-model:prodNameCn="prodNameCn"
          v-model:prodNameEn="prodNameEn"
          :is-compose="dataForm.isCompose"
        />
      </div>

      <!-- 物流信息  -->
      <div class="logistics-box">
        <div
          v-show="postingSteps === 1"
          class="tittle "
        >
          {{ $t("order.logisticsInformation") }}
        </div>
        <div
          v-show="postingSteps === 1"
          class="basic-info"
        >
          <el-form-item :label="$t('order.delType')">
            <el-checkbox
              v-model="dataForm.deliveryMode.hasShopDelivery"
              disabled
            >
              {{ $t("order.ordinaryExpress") }}
            </el-checkbox>
            <el-checkbox v-model="dataForm.deliveryMode.hasUserPickUp">
              {{
                $t("product.userMention")
              }}
            </el-checkbox>
            <el-checkbox
              v-model="dataForm.deliveryMode.hasCityDelivery"
              :disabled="sameCityStatus === 0"
            >
              {{ $t("order.sameCityDelivery") }}
            </el-checkbox>
          </el-form-item>

          <ProdTransport
            v-show="dataForm.deliveryMode.hasShopDelivery"
            :transport-data="dataForm"
            @change-info="changeInfo"
          />
        </div>
      </div>
      <!-- 商品详细信息 -->
      <template v-if="postingSteps === 2">
        <div class="tittle">
          {{ $t("homes.productDetails") }}
        </div>
        <div class="basic-info basic-iny-mce">
          <el-tabs type="card">
            <el-tab-pane :label="$t('product.chinenInput')">
              <el-form-item
                :label="$t('homes.productDetails')"
                prop="contentCn"
              >
                <div class="prod-det-box">
                  <div class="prod-content">
                    <tiny-mce
                      ref="contentCnRef"
                      v-model="contentCn"
                      :height="600"
                    />
                  </div>

                  <!-- 详情预览 -->
                  <div class="details-preview">
                    <div class="preview-box-title">
                      {{ $t('sysManagement.DetailspagePreviewImage') }}
                    </div>
                    <div
                      v-rich="contentCn"
                      class="preview-con"
                    />
                  </div>
                </div>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane
              v-if="curLang.includes(2)"
              :label="$t('sysManagement.englishInformation')"
            >
              <el-form-item
                :label="$t('homes.productDetails')"
                prop="contentEn"
              >
                <div class="prod-det-box">
                  <div class="prod-content">
                    <TinyMce
                      ref="contentEnRef"
                      v-model="contentEn"
                      :height="600"
                    />
                  </div>
                  <!-- 详情预览 -->
                  <div class="details-preview">
                    <div class="preview-box-title">
                      {{ $t('sysManagement.DetailspagePreviewImage') }}
                    </div>
                    <div
                      v-rich="contentEn"
                      class="preview-con"
                    />
                  </div>
                </div>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
    </el-form>
    <!-- 底部固定操作栏 -->
    <div class="prod-footer">
      <div class="foot">
        <div class="inner">
          <div v-if="postingSteps === 1">
            <div
              class="default-btn save-btn"
              @click="onSubmit"
            >
              {{ $t("product.saveBtn1") }}
            </div>
            <div
              class="default-btn primary-btn"
              @click="onNextStep"
            >
              {{ $t("product.nextStep2") }}
            </div>
          </div>
          <div v-if="postingSteps === 2">
            <div
              class="default-btn save-btn"
              @click="onPrevStep"
            >
              {{ $t("product.prevStep") }}
            </div>
            <div
              class="default-btn primary-btn"
              @click="onSubmit"
            >
              {{ $t("product.saveBtn1") }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { useCommonStore } from '@/stores/common.js'
import { useRoute, useRouter } from 'vue-router'
import { validHtmlLength, treeDataTranslate, idList } from '@/utils/index.js'
import { reactive, ref, nextTick, onMounted } from 'vue'
import ImgsUpload from '@/components/imgs-upload/index.vue'
import VideoUpload from '@/components/video-upload/index.vue'
import TinyMce from '@/components/tiny-mce/index.vue'
import SkuTag from '@/components/sku-tag/index.vue'
import SkuTableProd from './components/sku-table.vue'
import ProdTransport from './components/prod-transport.vue'

const route = useRoute()
const router = useRouter()
const commonStore = useCommonStore()

const postingSteps = ref(1) // 步骤
// 语言选项
const curLang = ref([1])
const langOptions = [
  {
    value: 1,
    label: '简体中文'
  },
  {
    value: 2,
    label: 'English'
  }
]

// 分类树展示与回显
const category = reactive({
  list: [],
  selected: [],
  props: {
    value: 'categoryId',
    label: 'categoryName',
    checkStrictly: false,
    expandTrigger: 'hover'
  }
})

const prodNameCn = ref('')
const prodNameEn = ref('')
const contentEn = ref('')
const contentCn = ref('')
const briefEn = ref('')
const briefCn = ref('')
const sameCityStatus = ref(0)
const skuPartyCodes = ref(true)
const tags = ref([])
// 规格列表
const dataForm = ref({
  deliveryAmount: 0.01,
  tableRate: -1,
  prodName: '',
  brief: '',
  video: '',
  prodNameEn: '',
  prodNameCn: '',
  contentEn: '',
  contentCn: '',
  briefEn: '',
  briefCn: '',
  pic: '',
  imgs: '',
  preSellStatus: 0,
  preSellTime: null,
  categoryId: 0,
  prodId: 0,
  skuList: [],
  tagList: [],
  content: '',
  deliveryMode: {
    hasShopDelivery: true,
    hasUserPickUp: false,
    hasCityDelivery: false
  },
  deliveryTemplateId: -1,
  isCompose:
  route.query.isCompose != null ? parseInt(route.query.isCompose) : null
})

// 组件ref
const dataFormRef = ref(null)
const skuTagRef = ref(null)
const skuTableRef = ref(null)

let partyCode = ''
let isSubmit = false

onMounted(() => {
  dataForm.value.prodId = route.query.prodId
  dataForm.value.isCompose = route.query.isCompose
  isSubmit = false
  getDataList()
  getSameCityDetail()
})

// 上一步
const onPrevStep = () => {
  postingSteps.value = 1
}
// 下一步
const onNextStep = () => {
  dataFormRef.value?.validate((valid) => {
    if (!prodNameCn.value) {
      onErrorMsg($t('product.pleEnterProdName'))
      return
    }
    if (!dataForm.value.imgs) {
      onErrorMsg($t('product.plePictureToUpload'))
      return
    }
    if (category.selected.length === 0) {
      onErrorMsg($t('product.pleCategory'))
      return
    }

    if (skuTagRef.value.skuTags && skuTagRef.value.skuTags.length === 1 && !skuTagRef.value.skuTags[0].tagItems.length) {
      onErrorMsg($t('product.attributeValueNoNull'))
      return
    }

    if (dataForm.value.isCompose == 1 && !dataForm.value.skuList.every((item) => item.skuSingleProds && item.skuSingleProds.length)) {
      onErrorMsg($t('product.postProductTips25'))
      return
    }
    if (!dataForm.value.deliveryMode) {
      onErrorMsg($t('product.pleeliveryMethod'))
      return
    }
    if ((dataForm.value.deliveryAmount === 0 || dataForm.value.deliveryAmount === '' || dataForm.value.deliveryAmount === null) && dataForm.value.tableRate === -1) {
      // 请选择运费模板
      onErrorMsg($t('menuList.pleaseEnterTheAmount'))
      return
    }
    if (dataForm.value.deliveryMode.hasShopDelivery && dataForm.value.tableRate > 0 && !dataForm.value.deliveryTemplateId) {
      onErrorMsg($t('product.pleShgTlate'))
      return
    }

    if (dataForm.value.preSellStatus && !dataForm.value.preSellTime) {
      onErrorMsg($t('product.thePreSaleDtBeEmpty'))
      return
    }
    if (!valid) {
      return
    }
    if (/^\s+$/g.test(briefCn.value) || /^\s+$/g.test(briefEn.value)) {
      onErrorMsg(
        $t('product.prodellingPoint') +
          $t('canNotBeSpace')
      )
      return
    }
    if (
      validHtmlLength(dataForm.value.contentCn) ||
      validHtmlLength(dataForm.value.contentEn)
    ) {
      return
    }
    if (briefCn.value && briefCn.value.length > 500) {
      ElMessage.error(
        $t('product.prodellingPoint') +
          $t('LengthLess500')
      )
      return
    }
    postingSteps.value = 2
  })
}
/**
 * 选择语言(中文信息必填)
 */
const onSelectLang = (value) => {
  if (!value.length) {
    curLang.value = [1]
    return
  }
  curLang.value = JSON.parse(JSON.stringify(value))
  if (!curLang.value.find((el) => el === 2)) {
    dataForm.value.prodLangList.forEach((el) => {
      if (el.lang === 1) {
        el.prodNameEn = ''
        el.briefEn = ''
        dataForm.value.briefEn = ''
        dataForm.value.prodNameEn = ''
      }
    })
  }
  if (!curLang.value.find((el) => el === 1)) {
    curLang.value.unshift(1)
  }
}
/**
 * 获取店铺同城配送的配置
 */
const getSameCityDetail = () => {
  http({
    url: http.adornUrl('/delivery/sameCity/getSameCityInfo'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      sameCityStatus.value = data.status
    }
  })
}
// 获取分类数据
const getDataList = () => {
  getTagList()
  getCategoryList().then(() => {
    if (dataForm.value.prodId) {
      // 获取产品数据
      http({
        url: http.adornUrl(`/prod/prod/info/${dataForm.value.prodId}`),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.value = data
        dataForm.value.prodLangList.forEach((prodLang) => {
          if (prodLang.lang === 0) {
            prodNameCn.value = prodLang.prodName
            briefCn.value = prodLang.brief
            contentCn.value = prodLang.content
          }
          if (prodLang.lang === 1) {
            prodNameEn.value = prodLang.prodName
            briefEn.value = prodLang.brief
            contentEn.value = prodLang.content
          }
        })

        if (prodNameEn.value !== prodNameCn.value || briefEn.value !== briefCn.value || contentEn.value !== contentCn.value) {
          curLang.value = [1, 2]
        }

        dataForm.value.deliveryMode = JSON.parse(data.deliveryMode)
        skuTagRef.value.init(data.skuList)
        dataForm.value.skuList.forEach((sku) => {
          sku.oriStock = sku.stocks
          sku.skuLangList.forEach((skulang) => {
            if (skulang.lang === 0) {
              sku.prodNameCn = skulang.prodName
            } else {
              sku.prodNameEn = skulang.prodName
            }
          })
        })
        skuTableRef.value.init(dataForm.value.skuList)
        category.selected = idList(
          category.list,
          dataForm.value.categoryId,
          'categoryId',
          'children'
        ).reverse()
        dataForm.value.skuList.forEach((item) => {
          item.changeStock = item.stocks
        })
        dataForm.value.tagList = data.tagList
      }).catch(() => {})
    } else {
      nextTick(() => {
        dataFormRef.value.resetFields()
        skuTagRef.value?.init()
        dataForm.value.pic = ''
        dataForm.value.imgs = ''
        dataForm.value.video = ''
      })
    }
  })
}

// 获取分类信息
const getCategoryList = () => {
  return http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({ status: 1 })
  }).then(({ data }) => {
    // 仅展示含有三级分类的分类
    category.list = filterCategoryList(treeDataTranslate(data, 'categoryId', 'parentId'), 0)
  })
}
/**
 * 仅展示含有三级分类的分类
 */
const filterCategoryList = (categories, level) => {
  return categories.filter((item) => {
    // 当前项是否含有下级分类
    if (item.children && item.children.length > 0) {
      item.children = filterCategoryList(item.children, level + 1)
    }
    return showCategory(item, level)
  })
}
const showCategory = (item, level) => {
  // 一级分类时，判断是否含有二级分类且二级分类下是否含有三级分类
  if (level === 0) {
    return (
      item.children &&
      item.children.length &&
      item.children.some((el) => showCategory(el, level + 1))
    )
  }
  // 二级分类时，判断是否含有三级分类
  if (level === 1) {
    return !!(item.children && item.children.length)
  }
  return true
}

// 选择分类改变事件
const handleCategoryChange = (val) => {
  dataForm.value.categoryId = val[val.length - 1]
}
// 表单提交
const onSubmit = () => {
  dataFormRef.value.validate((valid) => {
    if (!prodNameCn.value) {
      onErrorMsg($t('product.pleEnterProdName'))
      return
    }
    if (!dataForm.value.imgs) {
      onErrorMsg($t('product.plePictureToUpload'))
      return
    }
    if (category.selected.length === 0) {
      onErrorMsg($t('product.pleCategory'))
      return
    }
    if (skuTagRef.value.skuTags && skuTagRef.value.skuTags.length === 1 && !skuTagRef.value.skuTags[0].tagItems.length) {
      onErrorMsg($t('product.attributeValueNoNull'))
      return
    }

    if (dataForm.value.isCompose == 1 && !dataForm.value.skuList.every((item) => item.skuSingleProds && item.skuSingleProds.length)) {
      onErrorMsg($t('product.postProductTips25'))
      return
    }
    if (!dataForm.value.deliveryMode) {
      onErrorMsg($t('product.pleeliveryMethod'))
      return
    }
    if ((dataForm.value.deliveryAmount === 0 || dataForm.value.deliveryAmount === '' || dataForm.value.deliveryAmount === null) && dataForm.value.tableRate === -1) {
      // 请选择运费模板
      onErrorMsg($t('menuList.pleaseEnterTheAmount'))
      return
    }
    if (dataForm.value.deliveryMode.hasShopDelivery && dataForm.value.tableRate > 0 && !dataForm.value.deliveryTemplateId) {
      // 请选择运费模板
      onErrorMsg($t('product.pleShgTlate'))
      return
    }
    if (dataForm.value.preSellStatus && !dataForm.value.preSellTime) {
      onErrorMsg($t('product.thePreSaleDtBeEmpty'))
      return
    }
    if (!valid) {
      return
    }
    if (!prodNameEn.value || /^\s+$/g.test(prodNameEn.value)) {
      prodNameEn.value = prodNameCn.value
    }
    if (/^\s+$/g.test(briefCn.value) || /^\s+$/g.test(briefEn.value)) {
      onErrorMsg(
        $t('product.prodellingPoint') +
          $t('canNotBeSpace')
      )
      return
    }
    if (
      validHtmlLength(dataForm.value.contentCn) ||
      validHtmlLength(dataForm.value.contentEn)
    ) {
      return
    }
    if (briefCn.value && briefCn.value.length > 500) {
      ElMessage.error(
        $t('product.prodellingPoint') +
          $t('LengthLess500')
      )
      return
    }

    if (dataForm.value.tableRate === -1) {
      dataForm.value.deliveryTemplateId = -1
    } else if (dataForm.value.tableRate === 0) {
      dataForm.value.deliveryTemplateId = 0
    }

    if (!briefEn.value) {
      briefEn.value = briefCn.value
    }
    dataForm.value.brief = briefCn.value
    dataForm.value.prodNameCn = prodNameCn.value
    dataForm.value.briefCn = briefCn.value
    dataForm.value.contentCn = contentCn.value
    dataForm.value.prodNameEn = prodNameEn.value
    dataForm.value.briefEn = briefEn.value
    dataForm.value.contentEn = contentEn.value
    dataForm.value.prodName = dataForm.value.prodNameCn
    dataForm.value.skuList.forEach((item) => {
      if (!item.skuName) {
        item.skuName = ''
        item.skuNameEn = ''
      }
    })
    const param = Object.assign({}, dataForm.value)
    // 设置价格和库存
    const flag = paramSetPriceAndStocks(param)
    if (flag === false) {
      return
    }
    if (partyCode != null && skuPartyCodes.value) {
      onErrorMsg(
        $t('product.commodityCode') +
          partyCode +
          $t('product.isExistsPleaReEn')
      )
      return
    }
    if ((dataForm.value.contentCn && dataForm.value.contentCn.length > 20000) || (dataForm.value.contentEn && dataForm.value.contentEn.length > 20000)) {
      return ElMessage({
        message: $t('product.tinyMceTip'),
        type: 'error',
        duration: 1500
      })
    }

    param.deliveryMode = undefined
    param.deliveryModeVo = dataForm.value.deliveryMode
    dataForm.value.skuList.forEach((item) => {
      item.changeStock = item.stocks - item.oriStock
    })
    // 商品主图
    param.pic = dataForm.value.imgs.split(',')[0]
    if (isSubmit) {
      return false
    }
    isSubmit = true
    http({
      url: http.adornUrl('/prod/prod'),
      method: param.prodId ? 'put' : 'post',
      data: http.adornData(param)
    })
      .then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            commonStore.removeMainActiveTab()
            const routeList = commonStore.routeList
            const flag = routeList.some(
              (item) => item.url === 'prod/prod/index'
            )
            if (!flag) {
              router.push({ name: 'home' })
            } else {
              router.push({ path: '/prod/prod/index' })
            }
          }
        })
      })
      .catch(() => {
        isSubmit = false
      })
  })
}
const changeInfo = (info) => {
  dataForm.value.deliveryTemplateId = info.transportId
  dataForm.value.tableRate = info.tableRate
  dataForm.value.deliveryAmount = info.deliveryAmount
}
const paramSetPriceAndStocks = (param) => {
  // 商品库存
  param.totalStocks = 0
  // 商品价格
  param.price = 0
  // 商品原价
  param.oriPrice = 0
  // 商品实际库存
  const partyCodes = []
  skuPartyCodes.value = false
  for (let i = 0; i < param.skuList.length; i++) {
    const element = param.skuList[i]
    if (
      element.partyCode != null &&
      element.partyCode !== '' &&
      partyCodes.indexOf(element.partyCode) !== -1
    ) {
      partyCode = element.partyCode
      skuPartyCodes.value = true
      onErrorMsg($t('product.commodityCodeCannotBeRepeated'))
      return false
    }
    if (element.status !== 1) {
      continue
    }
    param.totalStocks += element.stocks ? Number.parseInt(element.stocks) : 0
    if (param.price === 0) {
      param.price = element.price ? Number.parseFloat(element.price) : 0
    }
    // 商品价格为最低价的那件商品的价格
    param.price = Math.min(param.price, element.price)
    if (param.price === parseFloat(element.price)) {
      param.oriPrice = element.oriPrice ? Number.parseFloat(element.oriPrice) : 0
    }
    partyCodes.push(element.partyCode)
  }
  // 如果sku没有商品名称，则使用商品的商品名称
  if (param.skuList.length === 1 && !param.skuList[0].skuName) {
    param.skuList[0].prodNameCn = dataForm.value.prodNameCn
    param.skuList[0].prodNameEn = dataForm.value.prodNameEn
  }
}
const skuTagChangeSkuHandler = (skuList) => {
  skuList.forEach((sku) => {
    if (sku.properties) {
      sku.skuName = ''
      sku.skuNameEn = ''
      const properties = sku.properties.split(';')
      const propertiesEn = sku.propertiesEn.split(';')
      for (const propertiesKey in properties) {
        sku.skuName += properties[propertiesKey].substring(properties[propertiesKey].indexOf(':') + 1) + ' '
      }
      for (const propertiesKey in propertiesEn) {
        sku.skuNameEn += propertiesEn[propertiesKey].substring(propertiesEn[propertiesKey].indexOf(':') + 1) + ' '
      }
      sku.prodNameCn = prodNameCn.value + ' ' + sku.skuName
      sku.prodNameEn = prodNameEn.value + ' ' + sku.skuNameEn
    }
  })
  dataForm.value.skuList = skuList
}

const changeSkuImg = (properties, value) => {
  dataForm.value.skuList.forEach((item) => {
    if (item.properties.split(';')[0] === properties) {
      item.pic = value
    }
  })
}
const onErrorMsg = (message) => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}
// 获取所有的分组信息
const getTagList = () => {
  http({
    url: http.adornUrl('/prod/prodTag/listTagList'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    tags.value = data
  })
}
/**
 * 删除视频
 */
const onDeleteVideo = () => {
  dataForm.value.video = ''
}

</script>
<style lang="scss" scoped>
@use './add-or-update.scss';
</style>
